//UDPTest.java
package com.ylaihui.net;

import org.junit.Test;

import java.io.IOException;
import java.net.*;

public class UDPTest {
    @Test
    public void udpreceive() throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(65530);

        byte[] bytes = new byte[100];
        DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length);

        datagramSocket.receive(datagramPacket);

        String string = new String(datagramPacket.getData(), 0, datagramPacket.getLength());

        System.out.println(string);

        datagramSocket.close();
    }

    @Test
    public void udpsend() throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket();

        byte[] bytes = "udp send message!".getBytes();
        InetAddress localHost = InetAddress.getLocalHost();
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, localHost, 65530);

        datagramSocket.send(datagramPacket);

        datagramSocket.close();
    }
}
